package org.iartisan.wechatsdk.miniprogram


import org.iartisan.runtime.env.EnvContextConfig
import org.iartisan.runtime.utils.HttpRequestUtil
import org.iartisan.wechatsdk.Utils._
import org.iartisan.wechatsdk.common.res.WechatResError
import org.iartisan.wechatsdk.common.{Constant, GlobalCache}
import org.iartisan.wechatsdk.miniprogram.req.{GetWxacodeReq, GetwxacodeunlimitReq}
import org.iartisan.wechatsdk.{JAccessToken, LogAspect}

import scala.collection.JavaConverters._
import scala.collection.mutable._


/**
  * 微信小程序二维码
  *
  * @author King  2019/6/25
  */
object Wxacode extends LogAspect {

  private val url_getwxacodeunlimit = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s"

  private val url_getwxacode = "https://api.weixin.qq.com/wxa/getwxacode?access_token=%s"

  /**
    * 获取小程序码，适用于需要的码数量极多的业务场景
    * 通过该接口生成的小程序码，永久有效，数量暂无限制
    *
    * @param req
    * @return
    */
  def getWxacodeunlimit(req: GetwxacodeunlimitReq) = {
    send(url_getwxacodeunlimit, req, "getWxacodeunlimit")
  }

  private def send(url: String, _data: Any, method: String) = {
    //数据转json
    val data = _data.toJson
    val requestUrl = String.format(url, getAccessToken)
    val headers = Map("Content-Type" -> "image/jpeg").asJava
    val response = HttpRequestUtil.sendPost(requestUrl, data, headers)
    response.header("Content-Type") match {
      case content if content.startsWith("application/json") =>
        val wechatResError = response.body.string.toObject[WechatResError]
        log.error(s"${LOG_RES} $method,errcode:[${wechatResError.getErrcode}], errmsg:[${wechatResError.getErrmsg}]")
        throw new IllegalArgumentException("调用接口失败")
      case _ =>
        response.body().bytes
    }
  }

  def getAccessToken = {
    val appid = EnvContextConfig.get(Constant.wechat_miniapp_appid)
    val secret = EnvContextConfig.get(Constant.wechat_miniapp_secret)
    //获取accessToken
    var accessToken = GlobalCache.getAccessToken(appid)
    if (null == accessToken) {
      accessToken = JAccessToken.getAccessToken(appid, secret)
    }
    accessToken
  }

  /**
    * 获取有限制的二维码
    */
  def getWxacode(req: GetWxacodeReq) = {
    send(url_getwxacode, req, "getWxacode")
  }
}
